<?php
/**
 * Created by PhpStorm.
 * User: luzhaoyang
 * Date: 2017/7/20
 * Time: 14:49
 */

class Stat_model extends Base_Model
{
    public $_redis;
    public function __construct()
    {
        parent::__construct();
        $this->load->database();
        $this->load->model('redis_model');
        $this->_redis=$this->redis_model->getRedisInstance();
    }

    public function commlogin($start,$end)
    {
        $starttime=strtotime($start);
        $endtime=strtotime($end);
        $statid=$start.':'.$end;//统计id

        $daytime=86400;

        $limit=10;
        $offset=0;

        $this->_redis->delete('stat:'.$statid.':login');//清空之前的统计
        try{
            $dur=time();
            while(true){
                $this->db->reconnect();
                $users=$this->db->select('uid')->from('mod_user')->limit($limit,$offset)->get()->result_array();
                if (empty($users)) break;//用户遍历完毕
                foreach ($users as $u){
                    $cur=$starttime;
                    //遍历每日登陆信息
                    while($cur<$endtime||$cur==$endtime){
                        $islogin=$this->_redis->getBit('commlogin:'.date('Ymd',$cur),$u['uid']);
                        if ($islogin==1) {
                            $this->_redis->zIncrBy('stat:'.$statid.':login',1,$u['uid']);
                            echo 'user:'.$u['uid'].' '.date('Y-m-d',$cur).' logined'.PHP_EOL;
                        }
                        $cur+=$daytime;
                    }
                }
                $offset+=$limit;
            }
            $dur=time()-$dur;
            echo 'complete! totalTime:'.date('i:s',$dur).PHP_EOL;
        }catch (Exception $e){
            $this->db->close();
            echo $e->getMessage().PHP_EOL;
            exit();
        }
    }

    public function fmdkread($books)
    {
        $dur=time();
        $limit=10;
        $offset=0;
        $statid=md5($books);//统计id

        $this->_redis->delete('stat:'.$statid.':fmdkreadtime');
        $books=explode('.',$books);
        //查询音频时长
        $booktimedata=$this->db->select('time,qid')->from('comm_answer_audio')->where_in('qid',$books)->get()->result_array();
        $booktimes=array();
        foreach ($booktimedata as $t){$booktimes[$t['qid']]=(int)$t['time'];}
        try{
            while(true){
                $this->db->reconnect();
                $users=$this->db->select('uid')->from('mod_user')->limit($limit,$offset)->get()->result_array();
                if (empty($users)) break;//用户遍历完毕
                foreach ($users as $u){
                    //遍历阅读信息
                    foreach ($books as $book){
                        $isview=$this->_redis->getBit('question:'.$book.'.viewsraw',$u['uid']);
                        if ($isview==1){
                            $this->_redis->zIncrBy('stat:'.$statid.':fmdkreadtime',$booktimes[$book],$u['uid']);//统计收听时间
                            $this->_redis->sAdd('stat:fmdkread:'.$u['uid'],$book);//统计每人收听了哪些音频
                            echo 'user:'.$u['uid'].' book'.$book.' readed'.PHP_EOL;
                        }
                    }
                }
                $offset+=$limit;
            }
            $dur=time()-$dur;
            echo 'complete! totalTime:'.date('i:s',$dur).PHP_EOL;
        }catch (Exception $e){
            $this->db->close();
            echo $e->getMessage().PHP_EOL;
            exit();
        }
    }

    public function share()
    {
        $index=0;
        try{
            while (true){
                $share=$this->_redis->lPop('shareoplist');
                if (!$share) break;
                $share=igbinary_unserialize($share);
                $data=array();
                $data['uid']=isset($share['uid'])?(int)$share['uid']:0;
                $data['type']=isset($share['type'])?$share['type']:'appmsg';
                $data['pid']=isset($share['data']['pid'])?(int)$share['data']['pid']:0;
                $data['page']=isset($share['data']['page'])?$share['data']['page']:'';
                $data['param']=isset($share['data']['param'])?$share['data']['param']:'';
                if (isset($share['created'])) $data['created']=(int)$share['created'];
                else $data['created']=isset($share['data']['created'])?$share['data']['created']:0;

                $this->db->reconnect();
                $this->db->insert('stat_share',$data);
                $index++;
                echo $index.' user '.$data['uid'].' shared '.$data['pid'].' '.$data['page'].' '.$data['param'].PHP_EOL;
            }
        }catch (Exception $e){
            echo $e->getMessage().PHP_EOL;
            $this->db->close();
            exit();
        }
    }

    public function saveFmdkstatData($start,$end,$books)
    {
        $dur=time();
        $booksstatid=md5($books);
        $books=explode('.',$books);

        try{
            $booktitles=$this->db->select('id,question')->from('comm_question')->where_in('id',$books)->get()->result_array();
            $booktitlesarr=array();
            foreach ($booktitles as $t){
                $posl=stripos($t['question'],'《');
                $posr=stripos($t['question'],'》');
                $len=$posr-$posl+3;
                $title=substr($t['question'],$posl,$len);
                $booktitlesarr[$t['id']]=$title;
            }

            $limit=10;
            $begin=0;
            $stop=$begin+$limit-1;
            $totaluser=0;
            $readuser=0;
            while (true){
                $logindata=$this->_redis->zRevRange('stat:'.$start.':'.$end.':login',$begin,$stop,TRUE);
                if (empty($logindata)) break;
                foreach ($logindata as $uid=>$l){
                    $data=array();

                    $data['time']=$this->_redis->zScore('stat:'.$booksstatid.':fmdkreadtime',$uid);
                    $data['time']=$data['time']==false?'0':$data['time'];//收听时长
                    if ($data['time']==0) continue;

                    $data['start']=strtotime($start);
                    $data['end']=strtotime($end);

                    $this->db->reconnect();
                    $qnum=$this->db->from('comm_question')->where(array('uid'=>$uid))->count_all_results();
                    $anum=$this->db->from('comm_answer')->where(array('uid'=>$uid))->count_all_results();
                    $cnum=$this->db->from('comm_comments')->where(array('uid'=>$uid))->count_all_results();
                    $shnum=$this->db->from('stat_share')->where(array('uid'=>$uid))->count_all_results();

                    $data['uid']=$uid;
                    $data['qnum']=$qnum;//提问次数
                    $data['ansnum']=$anum+$cnum;//回答次数+评论次数
                    $data['shnum']=$shnum;//分享次数
                    $data['login']=$l;//登陆天数

                    $ureadbooks = $this->_redis->sMembers('stat:fmdkread:'.$uid);
                    if (!empty($ureadbooks)){
                        $ureadbooksarr=array();
                        foreach ($ureadbooks as $b){
                            $ureadbooksarr[$b]=$booktitlesarr[$b];
                        }
                        $ureadbooks=array_flip(array_flip($ureadbooksarr));
                        $ureadbooks=count($ureadbooks);
                    }else{$ureadbooks=0;}
                    $data['books']=$ureadbooks;//阅读书数

                    $readuser++;

                    $this->db->insert('stat_fmdk',$data);

                    echo 'uid:'.$data['uid'].
                        ' qnum:'.$data['qnum'].
                        ' ansnum:'.$data['ansnum'].
                        ' shnum:'.$data['shnum'].
                        ' login:'.$data['login'].
                        ' time:'.$data['time'].
                        ' books:'.$data['books'].
                        PHP_EOL;
                }
                $totaluser+=count($logindata);
                $begin+=$limit;
                $stop+=$limit;
            }

            $dur=time()-$dur;
            echo 'complete! start:'.$start.' end:'.$end.' loginUser:'.$totaluser.' readUser:'.$readuser.' totalTime:'.date('i:s',$dur).PHP_EOL;
        }catch (Exception $e){
            $this->db->close();
            echo $e->getMessage().PHP_EOL;
            exit();
        }
    }
}